package com.ucode.wap.cgms.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.cgms.service.CgmsCompanionOrderReportLogService;
import com.ucode.cgms.service.CgmsCompanionOrderService;
import com.ucode.cgms.service.CgmsCompanionUserService;
import com.ucode.cgms.service.CgmsJointServiceUserService;
import com.ucode.model.cgms.CgmsCompanionOrderReportLog;
import com.ucode.model.cgms.CgmsJointServiceUser;
import com.ucode.model.cgms.convert.CgmsCompanionOrderReportLogConvert;
import com.ucode.model.cgms.enums.CgmsCompanionOrderStatusEnum;
import com.ucode.model.cgms.form.CgmsCompanionOrderAddReportLogForm;
import com.ucode.model.cgms.form.CgmsCompanionOrderCreateForm;
import com.ucode.model.cgms.form.CgmsCompanionOrderReportForm;
import com.ucode.model.cgms.form.CgmsCompanionOrderUpdateRemarkForm;
import com.ucode.model.cgms.vo.CgmsCompanionOrderVO;
import com.ucode.tool.annotation.NeedLogin;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.wap.base.core.CurrentLoginUserHandler;
import com.ucode.wap.cgms.service.ApiCgmsCompanionOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "移动端 - 陪玩社区系统 - 陪玩订单信息")
@RestController
@RequestMapping("/cgms/order")
@Validated
public class ApiCgmsCompanionOrderController {

    private static Log log = LogFactory.get();
    @Resource
    private ApiCgmsCompanionOrderService apiCgmsCompanionOrderService;
    @Resource
    private CgmsCompanionOrderService cgmsCompanionOrderService;
    @Resource
    private CgmsCompanionOrderReportLogService  companionOrderReportLogService;
    @Resource
    private CgmsJointServiceUserService cgmsJointServiceUserService;
    @Resource
    private CgmsCompanionUserService cgmsCompanionUserService;
    @Resource
    private CurrentLoginUserHandler currentLoginUserHandler;

    @NeedLogin
    @Operation(summary = "分页列表")
    @GetMapping(value = "/page-list")
    public ResponseResult<Paginator<CgmsCompanionOrderVO>> pageList(
            @Schema(description = "场景:(0 全部 1待付款 2派单中 3服务中 5 已完成 10 已取消)") @RequestParam(value = "scene",required=false) Integer scene,
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        Map<String,Object> condition = new HashMap<>();
        if(ObjUtil.equals(scene, 1)) {
            condition.put("status", CgmsCompanionOrderStatusEnum.PENDING_PAYMENT.getCode());
        }else if(ObjUtil.equals(scene, 2)){
            condition.put("status", CgmsCompanionOrderStatusEnum.DISPATCHING.getCode());
        }else if(ObjUtil.equals(scene, 3)){
            condition.put("statusList", Arrays.asList(CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode(), CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode()));
        }else if(ObjUtil.equals(scene, 5)){
            condition.put("statusList", Arrays.asList(CgmsCompanionOrderStatusEnum.END_SERVICE.getCode(), CgmsCompanionOrderStatusEnum.COMPLETED.getCode()));
        }else if(ObjUtil.equals(scene, 10)){
            condition.put("status", CgmsCompanionOrderStatusEnum.CANCELLED.getCode());
        }else{
            condition.put("statusList", Arrays.asList(CgmsCompanionOrderStatusEnum.DISPATCHING.getCode(),CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode(),CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode(),CgmsCompanionOrderStatusEnum.END_SERVICE.getCode(), CgmsCompanionOrderStatusEnum.COMPLETED.getCode(), CgmsCompanionOrderStatusEnum.AFTER_SALE.getCode(), CgmsCompanionOrderStatusEnum.AFTER_SALE_DONE.getCode()));
        }

        condition.put("memberId",currentLoginUserHandler.getCurrentUserId());
        condition.put("deltag",false);
        Paginator<CgmsCompanionOrderVO> paginator = apiCgmsCompanionOrderService.pageList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @NeedLogin
    @GetMapping("/details/{id}")
    @Parameter(description = "订单编码", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "订单信息详情")
    public ResponseResult<CgmsCompanionOrderVO> details(@PathVariable(name = "id", required = true) Long id) {
        return ResponseResult.success(apiCgmsCompanionOrderService.detail(id));
    }


    @NeedLogin(validate = true)
    @PostMapping("/submit")
    @Operation(summary = "提交订单")
    public ResponseResult<Long> submit(@Valid @RequestBody CgmsCompanionOrderCreateForm form) {
        return ResponseResult.success(apiCgmsCompanionOrderService.submitOrder(form));
    }

    @NeedLogin(validate = true)
    @PostMapping("/update-remark")
    @Operation(summary = "修改订单备注")
    public ResponseResult<Object> updateRemark(@Valid @RequestBody CgmsCompanionOrderUpdateRemarkForm form) {
        apiCgmsCompanionOrderService.updateRemark(form.getId(),form.getRemark());
        return ResponseResult.success();
    }

    @NeedLogin(validate = true)
    @PostMapping("/continue-pay")
    @Operation(summary = "继续支付")
    public ResponseResult<Long> continuePay(
            @Schema(description = "订单编号", requiredMode = Schema.RequiredMode.REQUIRED) @NotNull(message = "订单编号不能为空") @RequestParam(value = "orderId",required=true) Long orderId,
            @Schema(description = "支付应用编号", requiredMode = Schema.RequiredMode.REQUIRED) @NotNull(message = "支付应用编号不能为空")@RequestParam(value = "appId",required=true) Long appId ) {
        Long payOrderId = apiCgmsCompanionOrderService.continuePay(orderId,appId);
        return ResponseResult.success(payOrderId);
    }


    @NeedLogin(validate = true)
    @PostMapping("/cancel/{id}")
    @Parameter(description = "订单编号", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "取消订单")
    public ResponseResult cancel(@PathVariable(name = "id", required = true) Long id) {
        apiCgmsCompanionOrderService.cancel(id);
        return ResponseResult.success();
    }

    @NeedLogin(validate = true)
    @PostMapping("/delete/{id}")
    @Parameter(description = "订单编号", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "删除订单")
    public ResponseResult delete(@PathVariable(name = "id", required = true) Long id) {
        apiCgmsCompanionOrderService.delete(id);
        return ResponseResult.success();
    }

    @NeedLogin(validate = true)
    @PostMapping("/confirm-completed/{id}")
    @Parameter(description = "订单编号", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "确认完工")
    public ResponseResult confirmCompleted(@PathVariable(name = "id", required = true) Long id) {
        apiCgmsCompanionOrderService.confirmCompleted(id);
        return ResponseResult.success();
    }


    @NeedLogin(validate = true)
    @PostMapping("/confirm-receive/{id}")
    @Parameter(description = "订单编号", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "陪玩确认接单")
    public ResponseResult confirmReceive(@PathVariable(name = "id", required = true) Long id) {
        apiCgmsCompanionOrderService.confirmReceive(id);
        return ResponseResult.success();
    }

    @NeedLogin(validate = true)
    @PostMapping("/refuse-receive/{id}")
    @Parameter(description = "订单编号", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "陪玩拒绝接单")
    public ResponseResult refuseReceive(@PathVariable(name = "id", required = true) Long id) {
        apiCgmsCompanionOrderService.refuseReceive(id);
        return ResponseResult.success();
    }

    @NeedLogin(validate = true)
    @PostMapping("/add-report-log")
    @Operation(summary = "添加报备日志")
    public ResponseResult<Object> addReportLog(@Valid @RequestBody CgmsCompanionOrderAddReportLogForm form) {
        CgmsJointServiceUser cgmsJointServiceUser = cgmsJointServiceUserService.queryOne(form.getId(),currentLoginUserHandler.getCurrentUserId());
        if(ObjUtil.isNull(cgmsJointServiceUser))
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);

        CgmsCompanionOrderReportLog bean = CgmsCompanionOrderReportLogConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        bean.setServiceUserId(cgmsJointServiceUser.getServiceUserId());
        companionOrderReportLogService.insert(bean);
        return ResponseResult.success();
    }

    @NeedLogin(validate = true)
    @PostMapping("/completed-report")
    @Operation(summary = "完工报备")
    public ResponseResult<Object> companionReport(@Valid @RequestBody CgmsCompanionOrderReportForm form) {
        apiCgmsCompanionOrderService.companionReport(form);
        return ResponseResult.success();
    }

    @NeedLogin
    @Operation(summary = "陪玩服务的订单分页列表")
    @GetMapping(value = "/companion-user/page-list")
    public ResponseResult<Paginator<CgmsCompanionOrderVO>> pageListByCompanionUser(
            @Schema(description = "场景:(0 全部 1待确认 2 服务中 3 已完成)") @RequestParam(value = "scene",required=false) Integer scene,
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        Map<String,Object> condition = new HashMap<>();
        if(ObjUtil.equals(scene, 1)) {
            condition.put("status", CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode());
        }else if(ObjUtil.equals(scene, 2)){
            condition.put("statusList", Arrays.asList(CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode(), CgmsCompanionOrderStatusEnum.END_SERVICE.getCode()));
        }else if(ObjUtil.equals(scene, 3)){
            condition.put("status", CgmsCompanionOrderStatusEnum.COMPLETED.getCode());
        }else if(ObjUtil.equals(scene, 4)){
            condition.put("afterSaleTag", true);
        }else {
            condition.put("statusList", Arrays.asList(CgmsCompanionOrderStatusEnum.DISPATCHING.getCode(),CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode(),CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode(),CgmsCompanionOrderStatusEnum.END_SERVICE.getCode(), CgmsCompanionOrderStatusEnum.COMPLETED.getCode(), CgmsCompanionOrderStatusEnum.AFTER_SALE.getCode(), CgmsCompanionOrderStatusEnum.AFTER_SALE_DONE.getCode()));
        }

        condition.put("orderServiceUserId",currentLoginUserHandler.getCurrentUserId());
        condition.put("deltag",false);
        Paginator<CgmsCompanionOrderVO> paginator = apiCgmsCompanionOrderService.pageList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }


    @NeedLogin
    @Operation(summary = "陪玩抢单分页列表")
    @GetMapping(value = "/companion-user/snatch-order/list")
    public ResponseResult<List<CgmsCompanionOrderVO>> companionUserSnatchOrderList() {
        List<CgmsCompanionOrderVO> paginator = apiCgmsCompanionOrderService.queryCompanionUserSnatchOrderList();
        return ResponseResult.success(paginator);
    }

    @NeedLogin(validate = true)
    @PostMapping("/snatch-order/{id}")
    @Parameter(description = "订单编号", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "陪玩抢单")
    public ResponseResult snatchOrder(@PathVariable(name = "id", required = true) Long id) {
        apiCgmsCompanionOrderService.snatchOrder(id);
        return ResponseResult.success();
    }


    @NeedLogin
    @Operation(summary = "管理中心的订单分页列表")
    @GetMapping(value = "/admin/page-list")
    public ResponseResult<Paginator<CgmsCompanionOrderVO>> pageListByAdmin(
            @Schema(description = "场景:(0 全部 1待确认 2 服务中 3 已完成 5 待派单)") @RequestParam(value = "scene",required=false) Integer scene,
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        cgmsCompanionUserService.validateCompanionUserIsAdmin(currentLoginUserHandler.getCurrentUserId());

        Map<String,Object> condition = new HashMap<>();
        if(ObjUtil.equals(scene, 1)) {
            condition.put("status", CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode());
        }else if(ObjUtil.equals(scene, 2)){
            condition.put("statusList", Arrays.asList(CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode(), CgmsCompanionOrderStatusEnum.END_SERVICE.getCode()));
        }else if(ObjUtil.equals(scene, 3)){
            condition.put("status", CgmsCompanionOrderStatusEnum.COMPLETED.getCode());
        }else if(ObjUtil.equals(scene, 5)){
            condition.put("status", CgmsCompanionOrderStatusEnum.DISPATCHING.getCode());
            condition.put("orderServiceUserId",0L);
        }else{
            condition.put("statusList", Arrays.asList(CgmsCompanionOrderStatusEnum.DISPATCHING.getCode(),CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode(),CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode(),CgmsCompanionOrderStatusEnum.END_SERVICE.getCode(), CgmsCompanionOrderStatusEnum.COMPLETED.getCode(), CgmsCompanionOrderStatusEnum.AFTER_SALE.getCode(), CgmsCompanionOrderStatusEnum.AFTER_SALE_DONE.getCode()));
        }
        condition.put("deltag",false);
        Paginator<CgmsCompanionOrderVO> paginator = apiCgmsCompanionOrderService.pageList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @NeedLogin
    @PostMapping("/designate/{orderId}/{userId}")
    @Operation(summary = "陪玩单分配")
    @Parameter(description="订单ID",name = "orderId", required = true,in = ParameterIn.PATH,example = "1024")
    @Parameter(description="陪玩用户ID",name = "userId", required = true,in = ParameterIn.PATH,example = "2048")
    public ResponseResult<Object> designateOrder(
            @PathVariable(name="orderId",required=true) Long orderId,
            @PathVariable(name="userId",required=true) Long userId) {

        cgmsCompanionUserService.validateCompanionUserIsAdmin(currentLoginUserHandler.getCurrentUserId());

        if (ObjectUtil.isNull(orderId) || ObjectUtil.isNull(userId)) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }
        // 验证陪玩用户存在
        cgmsCompanionUserService.validate(userId);
        cgmsCompanionOrderService.designateOrder(userId, orderId);
        return ResponseResult.success();
    }



}
